package com.example.blank700.note;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class NoteActivity extends AppCompatActivity {
    // 插入一条新纪录
    public static final int MENU_ITEM_INSERT = Menu.FIRST;
    // 编辑内容
    public static final int MENU_ITEM_EDIT = Menu.FIRST + 1;

    // GreenDAO使用的变量
    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private NoteDao noteDao;
    private Cursor cursor;

    private ListView listView;
    private SimpleCursorAdapter adapter;
    private SearchView searchView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note);

        //findBiewById
        FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);
        final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
        final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.note_view_layout);

        //悬浮按钮的监听器
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent0 = new Intent(NoteActivity.this, NoteEditor.class);
                intent0.setAction(NoteEditor.INSERT_DIARY_ACTION);
                intent0.setData(getIntent().getData());
                startActivity(intent0);
                NoteActivity.this.finish();
                cursor.requery();
            }
        });

        //侧滑菜单部分的监听器
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.tag_all:
                        refresh();
                        Toast.makeText(NoteActivity.this, item.getTitle(),
                                Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tag_important:
                        refresh(1);
                        Toast.makeText(NoteActivity.this, item.getTitle(),
                                Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tag_encryption:
                        refresh(2);
                        Toast.makeText(NoteActivity.this, item.getTitle(),
                                Toast.LENGTH_SHORT).show();
                        break;
                }
                drawerLayout.closeDrawer(navigationView);
                return false;
            }
        });

        //侧滑头部的监听器
        navigationView.getHeaderView(0).findViewById(R.id.icon_avatar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(NoteActivity.this, "不要戳兔兔啦！兔兔那么可爱！", Toast.LENGTH_SHORT).show();
                drawerLayout.closeDrawer(navigationView);
            }
        });

        //初始化greenDao
        InitDao();
        //初始化List
        InitList();
    }

    //初始化Dao
    private void InitDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
                null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        noteDao = daoSession.getNoteDao();
    }

    //初始化Lizt
    private void InitList() {
        //获取各个列的名称
        String textColumn = NoteDao.Properties.Title.columnName;
        String dateColumn = NoteDao.Properties.Date.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(), null,
                null, null, null, orderBy);
        String[] from = {textColumn, dateColumn};
        int[] to = {R.id.text1, R.id.created};
        adapter = new SimpleCursorAdapter(this, R.layout.note_row,
                cursor, from, to);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        //listView中点击item的监听器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String mid = Long.toString(id);
                Log.d("id", mid);

                //把item的id传给了NoteEditor
                Intent intent = new Intent(NoteActivity.this, NoteEditor.class);
                intent.setAction(NoteEditor.EDIT_DIARY_ACTION);
                Bundle bundle = new Bundle();
                bundle.putLong("id", id);
                intent.putExtras(bundle);
                Log.d("id", mid);
                startActivity(intent);
                NoteActivity.this.finish();
                cursor.requery();
            }
        })
        ;
        //添加长按菜单
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                //menu.setHeaderTitle("请选择操作");
                menu.add(0, 0, 0, "删除");//groupId,itemId,order,title
            }
        });
    }

    //重新装配listView
    public void refresh(){
        String textColumn = NoteDao.Properties.Title.columnName;
        String dateColumn = NoteDao.Properties.Date.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
                null, null, null,
                null, orderBy);
        String[] from = {textColumn, dateColumn};
        int[] to = {R.id.text1, R.id.created};
        adapter = new SimpleCursorAdapter(
                NoteActivity.this, R.layout.note_row, cursor, from, to);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
    }

    //重新装配listView
    public void refresh(int type){
        String textColumn = NoteDao.Properties.Title.columnName;
        String dateColumn = NoteDao.Properties.Date.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
                "tag = ?", new String[]{""+type+""}, null,
                null, orderBy);
        String[] from = {textColumn, dateColumn};
        int[] to = {R.id.text1, R.id.created};
        adapter = new SimpleCursorAdapter(
                NoteActivity.this, R.layout.note_row, cursor, from, to);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
    }

    //长按菜单选项响应函数
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        Long id = (Long) info.id;//获取元祖的id
        Log.e("id:", "id=" + info.id);
        switch (item.getItemId()) {
            case 0:
                noteDao.deleteByKey(id);
                Toast.makeText(NoteActivity.this, R.string.diary_delete_success,
                        Toast.LENGTH_SHORT).show();
                cursor.requery();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    //添加右上角的选择菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //配置顶部搜索框
        getMenuInflater().inflate(R.menu.search_menu,menu);
        MenuItem searchMenuItem=menu.findItem(R.id.search);
        searchView=(SearchView) MenuItemCompat.getActionView(searchMenuItem);
        searchView.setQueryHint("title of note");
        searchView.setSubmitButtonEnabled(true);
        //搜索框的监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.equals("")){
                    listView.setAdapter(adapter);
                }
                //传入查询的数据并更新listview
                searchFun(newText);
                return false;
            }
        });

        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, MENU_ITEM_INSERT, 0, R.string.menu_insert);
        return true;
    }

    //searchView查询方法
    public void searchFun(String newText){
        String textColumn = NoteDao.Properties.Title.columnName;
        String dateColumn = NoteDao.Properties.Date.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
                "title like ?", new String[]{"%"+newText+"%"}, null,
                null, orderBy);
        String[] from = {textColumn, dateColumn};
        int[] to = {R.id.text1, R.id.created};
        adapter = new SimpleCursorAdapter(
                NoteActivity.this, R.layout.note_row, cursor, from, to);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
    }

    //右上角菜单选项响应函数
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ITEM_INSERT:
                Intent intent0 = new Intent(this, NoteEditor.class);
                intent0.setAction(NoteEditor.INSERT_DIARY_ACTION);
                intent0.setData(getIntent().getData());
                startActivity(intent0);
                NoteActivity.this.finish();
                cursor.requery();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        cursor.requery();
        super.onActivityResult(requestCode, resultCode, data);
    }
}
